package com.lsh.controller;

import com.lsh.model.Admin;
import com.lsh.service.AdminService;
import com.lsh.util.JwtUtil;
import com.lsh.util.ResultObject;
import com.lsh.util.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ：LiuShihao
 * @date ：Created in 2020/11/3 1:44 下午
 * @desc ：
 */
//@RefreshScope
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    AdminService service;
    @Autowired
    JwtUtil jwtUtil;
    @PostMapping("/addAdmin")
    public ResultObject addAdmin(@RequestBody Admin admin){
        service.addAdmin(admin);
        return new ResultObject(true, StatusCode.OK,"添加管理员成功",null);
    }

    /**
     * 登录成功的同时生成jwt令牌,令牌交给前端处理
     * @param admin
     * @return
     */
    @PostMapping(value = "/login")
    public ResultObject login(@RequestBody Admin admin){
        Admin adminLogin = service.login(admin);
        if(adminLogin==null){
            return new ResultObject(false, StatusCode.LOGINERROR, "登录失败");
        }
        String jwt = jwtUtil.createJWT(adminLogin.getId(), adminLogin.getLoginname(), "admin", "crud");
        Map<String, Object> map = new HashMap<>();
        map.put("token", jwt);
        map.put("admin",adminLogin);
        return new ResultObject(true, StatusCode.OK, "登录成功",map);
    }
    /**
     * {
     *   "flag": true,
     *   "code": 20000,
     *   "message": "登录成功",
     *   "data": {
     *     "admin": {
     *       "id": "165092480235212800",
     *       "loginname": "admin",
     *       "password": "$2a$10$4u1SKuwYM2P0A.ziMw4lwuLE.HtR6TXGXNR/y3MoTlKuJ6D5KxD1u",
     *       "state": "0"
     *     },
     *     "token": "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxNjUwOTI0ODAyMzUyMTI4MDAiLCJzdWIiOiJhZG1pbiIsImlhdCI6MTYwNDM5MDg3Miwicm9sZXMiOiJhZG1pbiIsInBlcm1pc3Npb24iOiJjcnVkIiwiZXhwIjoxNjA0NDc3MjcyfQ.0lb02-5QzRNBCns5ZDoA8duXQQ45jgNILjRud5sdVHo"
     *   }
     * }
     */
    @DeleteMapping
    public ResultObject deleteById(String id){
        return service.deleteById(id);
    }

    @GetMapping("getToken")
    public ResultObject gettoken(){
        String jwt = jwtUtil.createJWT("1", "张三", "admin", "delete_anything");
        System.out.println(jwt);
        return new ResultObject(true, StatusCode.OK, "生成Token成功",jwt);

    }
}
